<template>
  <div class="hotwords-container">
    <div class="hotwords-header">
      <el-input v-model="searchName" placeholder="请输入内容" style="width: 200px; margin-right: 12px;" clearable />
      <el-button @click="handleSearch">检索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="danger" @click="openAddDialog">新建热词</el-button>
    </div>
    <el-table :data="pagedHotwords" style="width: 100%; margin-top: 18px;" border>
      <el-table-column prop="name" label="热词名称" min-width="200" />
      <el-table-column prop="order" label="排序" min-width="100" />
      <el-table-column prop="addTime" label="添加时间" min-width="200" />
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          <span :style="scope.row.status === '上线' ? 'color:#409eff;' : 'color:#aaa;'">{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180">
        <template #default="scope">
          <el-button type="primary" link size="small" @click="openEditDialog(scope.row, scope.$index)">编辑</el-button>
          <el-button type="warning" link size="small" @click="offlineHotword(scope.$index)">下线</el-button>
          <el-button type="danger" link size="small" @click="deleteHotword(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="hotwords-pagination">
      <el-pagination
        background
        layout="sizes, prev, pager, next, total"
        :total="filteredHotwords.length"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        @current-change="handlePageChange"
        @size-change="val => { pageSize = val; currentPage = 1; }"
        style="margin-top: 18px;"
      />
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogMode === 'add' ? '新建热词' : '编辑热词'" width="400px">
      <el-form :model="dialogForm">
        <el-form-item label="热词名称" label-width="80px">
          <el-input v-model="dialogForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="排序" label-width="80px">
          <el-input v-model.number="dialogForm.order" type="number" min="1" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态" label-width="80px">
          <el-select v-model="dialogForm.status" placeholder="请选择状态">
            <el-option label="上线" value="上线" />
            <el-option label="下线" value="下线" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDialog">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessageBox } from 'element-plus';

const STORAGE_KEY = 'hotwordsList';
function formatDateTime(date: Date) {
  const pad = (n: number) => n.toString().padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
function loadHotwordsList() {
  const stored = localStorage.getItem(STORAGE_KEY);
  if (stored) {
    try {
      return JSON.parse(stored);
    } catch {
      return null;
    }
  }
  return null;
}
const defaultList = [
  { name: '苹果', order: 1, addTime: '2020-02-20 12:00:00', status: '上线' },
  { name: '香蕉', order: 2, addTime: '2021-03-15 09:30:45', status: '上线' },
  { name: '橙子', order: 3, addTime: '2022-07-01 18:22:11', status: '上线' },
  { name: '葡萄', order: 4, addTime: '2023-11-28 21:05:59', status: '上线' },
];
const hotwordsList = ref(loadHotwordsList() || defaultList);
function saveHotwordsList() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(hotwordsList.value));
}
const searchName = ref('');
const filteredHotwords = computed(() => {
  if (!searchName.value) return hotwordsList.value;
  return hotwordsList.value.filter((item: any) => item.name.includes(searchName.value));
});
const pageSize = ref(10);
const currentPage = ref(1);
const pageSizes = [2, 5, 10];
const pagedHotwords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredHotwords.value.slice(start, start + pageSize.value);
});
function handlePageChange(page: number) {
  currentPage.value = page;
}
function handleSearch() {
  currentPage.value = 1;
}
function handleReset() {
  searchName.value = '';
  currentPage.value = 1;
}
// 新建/编辑弹窗
const dialogVisible = ref(false);
const dialogForm = ref({ name: '', order: 1, status: '上线' });
let dialogMode: 'add' | 'edit' = 'add';
let editIndex = -1;
function openAddDialog() {
  dialogMode = 'add';
  dialogForm.value = { name: '', order: 1, status: '上线' };
  dialogVisible.value = true;
  editIndex = -1;
}
function openEditDialog(row: any, index: number) {
  dialogMode = 'edit';
  dialogForm.value = { ...row };
  editIndex = hotwordsList.value.findIndex((item: any) => item.name === row.name && item.order === row.order);
  dialogVisible.value = true;
}
function saveDialog() {
  if (!dialogForm.value.name) return;
  if (dialogMode === 'add') {
    hotwordsList.value.push({
      ...dialogForm.value,
      addTime: formatDateTime(new Date()),
    });
  } else if (editIndex !== -1) {
    hotwordsList.value[editIndex] = {
      ...dialogForm.value,
      addTime: hotwordsList.value[editIndex].addTime,
    };
  }
  saveHotwordsList();
  dialogVisible.value = false;
}
function offlineHotword(index: number) {
  const name = hotwordsList.value[index].name;
  ElMessageBox.confirm(
    `确定要下线 <span style='color:#f56c6c'>${name}</span> 吗？`,
    '提示',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    hotwordsList.value[index].status = '下线';
    saveHotwordsList();
  });
}
function deleteHotword(index: number) {
  const name = hotwordsList.value[index].name;
  ElMessageBox.confirm(
    `确定要删除 <span style='color:#f56c6c'>${name}</span> 吗？`,
    '提示',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    hotwordsList.value.splice(index, 1);
    saveHotwordsList();
  });
}
</script>

<style scoped>
.hotwords-container {
  background: #fff;
  padding: 24px 18px 0 18px;
  min-height: 400px;
}
.hotwords-header {
  margin-bottom: 12px;
}
.hotwords-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>